package com.example.demo.Controller;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.common.QueryPageParam;
import com.example.demo.common.Result;
import com.example.demo.entity.Adoption;
import com.example.demo.entity.Pet;
import com.example.demo.service.IAdoptionService;
import com.example.demo.service.IPetService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author demo
 * @since 2025-02-28
 */
@RestController
@RequestMapping("/pet")
public class PetController {

    @Autowired
    private IPetService petService;

    @Autowired
    private IAdoptionService adoptionService;

    //新增
    @PostMapping("/save")
    public Result save(
                       @RequestParam("petNo") Integer petNo,
                       @RequestParam("petName") String petName,
                       @RequestParam("applyStatus") Integer applyStatus,
                       @RequestParam("petType") Integer petType,
                       @RequestParam("sex") Integer sex,
                       @RequestParam("content") String content,
                       @RequestParam("status") Integer status,
                       @RequestParam(value = "createTime") String createTime,
                       @RequestParam(value = "imageFile", required = false) MultipartFile imageFile){

        Pet pet = new Pet();
        pet.setPetNo(petNo);
        pet.setPetName(petName);
        pet.setApplyStatus(applyStatus);
        pet.setPetType(petType);
        pet.setSex(sex);
        pet.setContent(content);
        pet.setStatus(status);
        pet.setCreateTime(LocalDateTime.parse(createTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));

        try {
            if (imageFile != null && !imageFile.isEmpty()) {
                // 校验文件大小
                if (imageFile.getSize() > 2 * 1024 * 1024) {
                    return Result.fail();
                }
                //图片类型校验
                String contentType = imageFile.getContentType();
                if (!Arrays.asList("image/jpeg", "image/png").contains(contentType)) {
                    return Result.fail("仅支持JPEG/PNG格式");
                }
                pet.setPetImage(imageFile.getBytes());
                pet.setImageType(contentType);
            }
            boolean saveResult = petService.save(pet);
            return saveResult ? Result.suc() : Result.fail("数据库保存失败");
        } catch (IOException e) {
            e.printStackTrace();
            return Result.fail("文件处理失败: " + e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("系统异常: " + e.getMessage());
        }

    }
    //更新
    @PostMapping("/update")
    public Result update(@RequestParam Long id,
                         @RequestParam Integer petNo,
                         @RequestParam String petName,
                         @RequestParam Integer applyStatus,
                         @RequestParam Integer petType,
                         @RequestParam Integer sex,
                         @RequestParam String content,
                         @RequestParam Integer status,
                         @RequestParam(value = "createTime") String createTime,
                         @RequestParam(value = "imageFile", required = false) MultipartFile imageFile
    ){
        Pet pet = new Pet();
        pet.setId(id);
        pet.setPetNo(petNo);
        pet.setPetName(petName);
        pet.setApplyStatus(applyStatus);
        pet.setPetType(petType);
        pet.setSex(sex);
        pet.setContent(content);
        pet.setStatus(status);
        pet.setCreateTime(LocalDateTime.parse(createTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));

        try {
            if (imageFile != null && !imageFile.isEmpty()) {
                // 校验文件类型和大小
                if (!Arrays.asList("image/jpeg", "image/png").contains(imageFile.getContentType())) {
                    return Result.fail("仅支持JPEG/PNG格式");
                }
                if (imageFile.getSize() > 2 * 1024 * 1024) {
                    return Result.fail("文件大小超过2MB");
                }
                pet.setPetImage(imageFile.getBytes());
                pet.setImageType(imageFile.getContentType());
            }
            boolean success = petService.updateById(pet);
            return success ? Result.suc() : Result.fail("更新失败");
        } catch (IOException e) {
            e.printStackTrace();
            return Result.fail("系统异常: " + e.getMessage());
        }
    }

    //删除
    @GetMapping("/del")
    public Result del(@RequestParam Long id){
        return petService.removeById(id)?Result.suc():Result.fail();
    }

    //图片获取接口
    @GetMapping("/image/{id}")
    public void getImage(@PathVariable Long id, HttpServletResponse response)throws IOException {
        Pet pet = petService.getById(id);
        if (pet == null || pet.getPetImage() == null) {
            response.sendError(404, "Image not found");
            return;
        }
        String contentType = pet.getImageType();
        response.setContentType(contentType != null ? contentType : "image/jpeg");
        response.getOutputStream().write(pet.getPetImage());

    }

    //图片上传接口
    @PostMapping("/uploadImage")
    public Result uploadImage(@RequestParam("file") MultipartFile file,
                              @RequestParam String petId)
            throws IOException{
        if (file.isEmpty()) {
            return Result.fail();
        }
        if (!Arrays.asList("image/jpeg", "image/png").contains(file.getContentType())) {
            return Result.fail();
        }
        if (file.getSize() > 2 * 1024 * 1024) {
            return Result.fail();
        }
        Pet pet = petService.getById(petId);
        if (pet == null) {
            return Result.fail();
        }
        //直接存储二进制数据，文件类型
        pet.setImageType(file.getContentType());
        pet.setPetImage(file.getBytes());
        //更新用户数据
        return petService.updateById(pet) ? Result.suc() : Result.fail();
    }

    /*@PostMapping("/listPageA")
    public Result listPageA(@RequestBody QueryPageParam query) {
        HashMap param = query.getParam();
        Integer sex = (Integer) param.get("sex");
        Integer petType = (Integer) param.get("petType");
        String keywords = (String)param.get("keywords");

        Page<Adoption> page = new Page();
        page.setCurrent(query.getPageNum());
        page.setSize(query.getPageSize());

        LambdaQueryWrapper<Adoption> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(keywords) && !"null".equals(keywords)){
            lambdaQueryWrapper.and(wrapper ->
                    wrapper.like(Adoption::getPetNo, keywords)
                            .or()
                            .like(Adoption::getPetName, keywords)
                            .or()
                            .like(Adoption::getAdopterNo, keywords)
            );
        }

        // 种类筛选（petType）
        if (petType != null) {
            lambdaQueryWrapper.eq(Adoption::getPetType, petType);
        }
        // 性别筛选（sex）
        if (sex != null) {
            lambdaQueryWrapper.eq(Adoption::getSex, sex);
        }

        IPage<Adoption> result = adoptionService.page(page, lambdaQueryWrapper);
        return Result.suc(result.getRecords(), result.getTotal());
        IPage result = adoptionService.pageA(page,lambdaQueryWrapper);
        List<Adoption> records = result.getRecords();
        return  Result.suc(records,result.getTotal());

    }*/

    @PostMapping("/listPageP")
    public Result listPageP(@RequestBody QueryPageParam query) {
        HashMap param = query.getParam();
        Integer sex = (Integer) param.get("sex");
        Integer petType = (Integer) param.get("petType");
        String keywords = (String)param.get("keywords");

        Page<Pet> page = new Page();
        page.setCurrent(query.getPageNum());
        page.setSize(query.getPageSize());

        LambdaQueryWrapper<Pet> lambdaQueryWrapper = new LambdaQueryWrapper();
        if (StringUtils.isNotBlank(keywords) && !"null".equals(keywords)){
            lambdaQueryWrapper.and(wrapper ->
                    wrapper.like(Pet::getPetNo, keywords)
                            .or()
                            .apply("CAST(pet_no AS CHAR) LIKE {0}", "%"+keywords+"%")
                            .or()
                            .like(Pet::getPetName,keywords)
            );
        }
        // 种类筛选（petType）
        if (petType != null) {
            lambdaQueryWrapper.eq(Pet::getPetType, petType);
        }
        // 性别筛选（sex）
        if (sex != null) {
            lambdaQueryWrapper.eq(Pet::getSex, sex);
        }

        // 执行分页查询
        IPage<Pet> result = petService.page(page, lambdaQueryWrapper);
        List<Pet> records = result.getRecords();

        // 联表查询Adoption表获取apply_status
        records.forEach(pet -> {
            Adoption adoption = adoptionService.lambdaQuery()
                    .eq(Adoption::getPetNo, pet.getPetNo())
                    .orderByDesc(Adoption::getAdoptTime)
                    .last("LIMIT 1")
                    .one();
            pet.setApplyStatus(adoption != null ? adoption.getApplyStatus() : 2);
        });

        return  Result.suc(records,result.getTotal());

    }

}
